package com.dmgis.hndz.common.utils;
/**
 * @ProjectName: transform
 * @Package: com.qingyu.transform.utils
 * @ClassName: Word2PdfUtil
 * @Author: qingyu
 * @Description:
 * @Date: 2020/3/20 10:47
 * @Version: 1.0
 */
import com.aspose.slides.PdfOptions;
import com.aspose.words.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;

public class Word2PdfUtil {

    /**
     * The constant LOG.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(Word2PdfUtil.class);

    /**
     * 获取license
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            // 凭证
            String licenseStr =
                    "<License>\n" +
                            "  <Data>\n" +
                            "    <Products>\n" +
                            "      <Product>Aspose.Total for Java</Product>\n" +
                            "      <Product>Aspose.Words for Java</Product>\n" +
                            "    </Products>\n" +
                            "    <EditionType>Enterprise</EditionType>\n" +
                            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                            "  </Data>\n" +
                            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                            "</License>";
            InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            LOG.error("error:", e);
        }
        return result;
    }

    /**
     * Word 2 pdf.
     *
     * @param pdfFilePath   the pdf file path
     */
    public static void word2Pdf(String wordPath, String pdfFilePath) {
        FileOutputStream fileOS = null;
        // 验证License
        if (!getLicense()) {
            LOG.error("验证License失败！");
            return;
        }
        File inputWord = new File(wordPath);
        try {
         	//此处处理乱码和小方块
            //如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//            FontSettings.getDefaultInstance().setFontsFolders(
//                    new String[] {"/usr/share/fonts", "/usr/share/fonts/chinese"}
//                    , true);
//            FontSettings.getFontSubstitutes(
//                    "/usr/share/fonts/chinese");
            FontSettings.setFontsFolders(new String[]{"/usr/share/fonts","/usr/share/fonts/chinese"},true);
            Document doc = new Document(Files.newInputStream(inputWord.toPath()));
            fileOS = new FileOutputStream(new File(pdfFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, SaveFormat.PDF);
            setFilePermissions(pdfFilePath);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }


    /**
     * Word 2 pdf.
     *
     */
    public static byte[] word2Pdf(String wordPath) {
        byte[] bytes=null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        HttpURLConnection urlConnection=null;
        // 验证License
        if (!getLicense()) {
            LOG.error("验证License失败！");
            return bytes;
        }
        try {
            URL url = new URL(wordPath);
            urlConnection =(HttpURLConnection) url.openConnection();
            // 设置连接主机超时（单位：毫秒)
            urlConnection.setConnectTimeout(10000);
            //设置从主机读取数据超时（单位：毫秒)
            urlConnection.setReadTimeout(10000);

            //Windows环境字体路径
            FontSettings.setFontsFolder("C:\\Windows\\Fonts\\", true);

            //Linux环境下的字体路径
//            FontSettings.setFontsFolders(new String[]{"/usr/share/fonts","/usr/share/fonts/chinese"},true);


            Document doc = new Document(urlConnection.getInputStream());
            // 保存转换的pdf文件
            doc.save(outputStream, SaveFormat.PDF);
            bytes=outputStream.toByteArray();

        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if (urlConnection!=null){
                    urlConnection.disconnect();
                }
                outputStream.close();
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
        return bytes;
    }
    private static void setFilePermissions(String filePath) {
        try {
            Runtime.getRuntime().exec("chmod 777 " + filePath);
            System.out.println("文件权限已设置为 777。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
